define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'admin/index',
                    add_url: 'admin/add',
                    edit_url: 'admin/edit',
                    del_url: 'admin/del',
                    multi_url: 'admin/multi',
                    import_url: 'admin/import',
                }
            });

            var table = $("#table");
            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, json) {
                var bt=table.data("bootstrap.table");
                if (bt){
                    bt.$toolbar.find(".export").find(".icon-share").text(" 导出");
                }
                $("tbody tr[data-index]", this).each(function () {
                    if (parseInt($("td:eq(1)", this).text()) == Config.admin.id) {
                        $("input[type=checkbox]", this).prop("disabled", true);
                    }
                });
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'a.id',
                sortName: 'a.id',
                fixedColumns: true,
                fixedRightNumber: 1,
                visible: false,
                showToggle: false,
                showColumns: false,
                search:false,
                showExport: true,
                columns: [
                    [
                        {field: 'state', checkbox: true, },
                        {field: 'a.id', title: 'ID'},
                        {field: 'username', title: '账号', operate:'LIKE'},
                        {field: 'nickname', title: '姓名', operate:'LIKE'},
                        {field: 'id_card', title: '身份证号', operate:'LIKE'},
                        {field: 'at.name', title: '身份', operate:'LIKE'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'status', title: __("Status"), operate:false, searchList: {"normal":'正常',"hidden":'冻结'}, formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'),
                            buttons: [
                                // {
                                //     name: 'freeze',
                                //     text: '冻结',
                                //     confirm: '确定操作吗？',
                                //     icon: '',
                                //     classname: 'btn btn-xs btn-primary btn-ajax',
                                //     url: 'admin/freeze',
                                //     success: function (data, ret) {
                                //         $(".btn-refresh").trigger("click");
                                //         //如果需要阻止成功提示，则必须使用return false;
                                //         //return false;
                                //     },
                                // },
                                // {
                                //     name: 'unfreeze',
                                //     text: '解冻',
                                //     confirm: '确定操作吗？',
                                //     icon: '',
                                //     classname: 'btn btn-xs btn-primary btn-ajax',
                                //     url: 'admin/unfreeze',
                                //     success: function (data, ret) {
                                //         $(".btn-refresh").trigger("click");
                                //         //如果需要阻止成功提示，则必须使用return false;
                                //         //return false;
                                //     },
                                // },
                                {
                                    name: 'edit',
                                    text: '编辑',
                                    icon: 'fa fa-pencil',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    url: 'admin/edit',
                                },
                                {
                                    name: '课程基准表管理',
                                    text: __('查看课程基准表'),
                                    extend: 'data-area=\'["80%","90%"]\' data-shade=\'[0.5,"#000"]\' data-toggle="tooltip"',
                                    icon: 'fa fa-list',
                                    classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                    url: 'auth/timetable/index'
                                },
                            ],
                            table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            formatter: function (value, row, index) { //隐藏自定义的视频按钮
                                var group_id = Config.group_id;
                                console.log(group_id);
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                //权限判断
                                if(row.status == 'hidden'){
                                    $(table).data("operate-freeze", null);
                                }
                                if(row.status == 'normal'){
                                    $(table).data("operate-unfreeze", null);
                                }
                                if(!(group_id == 1 || group_id == 6) && row.group_id == 8){ //非最高权限不能操作系统管理员
                                    $(table).data("operate-freeze", null);
                                    $(table).data("operate-unfreeze", null);
                                    $(table).data("operate-edit", null);
                                }
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });
            table.on('load-success.bs.table',function(data){
                $(".btn-editone").data("area", ["95%","95%"]);
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        freeze: function () {
            Controller.api.bindevent();
        },
        unfreeze: function () {
            Controller.api.bindevent();
        },
        teacher_select: function () {
            var multiple = Backend.api.query('multiple');
            multiple = multiple === 'true';
            var staff_type = Backend.api.query('staff_type');

            var clubs_name = Backend.api.query('clubs_name');
            var select_type = Backend.api.query('select_type');
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'admin/teacher_select',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                visible: false,
                showToggle: false,
                showColumns: false,
                search:false,
                showExport: false,
                searchFormVisible: true,
                queryParams: function (params) {
                    params['clubs_name'] = clubs_name;
                    params['select_type'] = select_type;
                    return params;
                },
                columns: [
                    [
                        {field: 'state', checkbox: multiple, visible: multiple, operate: false},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'nickname', title: '老师姓名', operate: 'LIKE'},
                        {field: 'name', title: '年级组', operate: 'LIKE'},
                        {
                            field: 'operate', title: __('Operate'), events: {
                                'click .btn-chooseone': function (e, value, row, index) {
                                    Fast.api.close([row]);
                                },
                            }, formatter: function () {
                                return '<a href="javascript:;" class="btn btn-danger btn-chooseone btn-xs"><i class="fa fa-check"></i> ' + __('Choose') + '</a>';
                            }
                        }
                    ]
                ]
            });

            // 选中多个
            $(document).on("click", ".btn-choose-multi", function () {
                Fast.api.close(table.bootstrapTable('getOptions').selectedData);
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {
                var group = $('#c-group').val();
                set_display(group);
                $('#c-group').change(function(){
                    var group = $(this).children('option:selected').val();
                    set_display(group);
                    var tbody = document.querySelector('#benchmark-table tbody');
                    // 移除tbody内的所有行
                    while (tbody.firstChild) {
                        tbody.removeChild(tbody.firstChild);
                    }
                });
                function set_display(group)
                {
                    if(group == 12){
                        $(".teacher").css({"display":"block"});
                    }else{

                        // $(".teacher").css({"display":"none"});
                    }
                    $("#select_salary").data('group',group);
                }

                var setBenchmark = function (data) {
                    var benchmark = '';
                    var ids = [];
                    $('#benchmark-table').find('tbody tr').each(function () {
                        ids.push($(this).data('id'));
                    });
                    for (var index in data) {
                        data[index].num = data[index].num || 0;

                        // 去重
                        if (ids.indexOf(data[index].id) !== -1) continue;
                        var tr = $('#tr-tpl').html();
                        for (var key in data[index]) {
                            tr = tr.replace(new RegExp("__"+ key +"__", 'g'), data[index][key]);
                        }
                        benchmark += tr;
                    }
                    $('#benchmark-table tbody').append(benchmark).closest('.box').show();
                };
                $(document).on('click', '[data-operate="remove"]', function () {
                    $(this).closest('tr').remove();
                });
                Fast.api.benchmark_Select('.select', {
                    multiple: true,
                    type:true,
                    callback: function (data) {
                        setBenchmark(data);
                    }
                });
                Form.api.bindevent($("form[role=form]"), null, null, function () {

                    var salary_benchmark_item_ids = ''; // 存储推荐产品组数据的数组
                    $('#benchmark-table').find('tbody tr').each(function () {
                        var id = $(this).data('id'); // 获取data-id属性的值
                        if ($(this).closest('table').attr('id') === 'benchmark-table') {
                            salary_benchmark_item_ids += id+',';
                        }
                    });

                    // 去除字符串末尾的逗号
                    salary_benchmark_item_ids = salary_benchmark_item_ids.slice(0, -1);
                    $('[name="row[salary_benchmark_item_id]"]').val(salary_benchmark_item_ids);
                });
            }
        }
    };

    return Controller;
});
